package cn.itsource.Lucene;

import org.apache.lucene.analysis.core.SimpleAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.*;
import org.apache.lucene.search.*;
import org.apache.lucene.store.*;
import org.junit.Test;

import java.io.IOException;
import java.nio.file.Paths;
import java.util.Collection;

public class LucenDemo {
    //创建索引库
    // 1. 准备文档
    String str1 = "hello world";
    String str2 = "hello Java";
    String str3 = "Hello java World";

    //2. 准备索引库
    String path ="D:\\IdeaProjects\\ElasticSearchDemo2\\lucene-index";

    @Test
    public void creatIndex() throws IOException {
    // 创建索引库
        // Directory d, 索引库存放的目录
        Directory d = new SimpleFSDirectory(Paths.get(path));

        // IndexWriterConfig conf  // 索引的配置 -- 需要分词器
        IndexWriterConfig conf = new IndexWriterConfig(new SimpleAnalyzer());

        IndexWriter indexWriter = new IndexWriter(d,conf);

    // 封装文档对象

        Document document1 = new Document();
        // name 字段名  value 值, store 是否存储
        document1.add(new TextField("title","str1", Field.Store.YES));
        document1.add(new TextField("content",str1, Field.Store.YES));
        // 添加
        indexWriter.addDocument(document1);

        Document document2 = new Document();
        // name 字段名  value 值, store 是否存储
        document2.add(new TextField("title","str2", Field.Store.YES));
        document2.add(new TextField("content",str2, Field.Store.YES));
        // 添加
        indexWriter.addDocument(document2);

        Document document3 = new Document();
        // name 字段名  value 值, store 是否存储
        document3.add(new TextField("title","str3", Field.Store.YES));
        document3.add(new TextField("content",str3, Field.Store.YES));
        // 添加
        indexWriter.addDocument(document3);

        // 提交
        indexWriter.commit();

        // 释放资源
        indexWriter.close();
    }

    @Test
    public  void search() throws IOException {
        // 连接索引库 索引库存放的目录
        Directory d = new SimpleFSDirectory(Paths.get(path));

        // 创建 IndexSearcher
        IndexReader indexReader = DirectoryReader.open(d);
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);

        // Query query 查询条件
        // int n 查询数量
        // String fld 查哪个字段 , String text 关键字
        Query query = new TermQuery(new Term("content","hello"));
        TopDocs search = indexSearcher.search(query, 20);

        System.out.println("命中："+search.totalHits);
        ScoreDoc[] scoreDocs = search.scoreDocs;
        for (ScoreDoc scoreDoc : scoreDocs) {
            // 通过文档的ID 查询到文档
            Document doc = indexSearcher.doc(scoreDoc.doc);
            System.out.println(doc.get("content"));
        }
    }

}
